'use strict';

var http = require("../utils/http");
var logger = require('../utils/log');
var constant = require('../utils/constant');

var redis = require("../utils/redis");
var db = require("../utils/db");

var room_service = require('./room_service');
// var user_service = require('./user_service');

var config = null;

var express = require('express');
var app = express();
var requestInfo = {};

exports.start = function(cfg){
	config = cfg;
	app.listen(config.SERVER_PORT);
	console.log("http server is listening on " + config.SERVER_PORT);
}

//设置跨域访问
app.all('*', function(req, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "X-Requested-With");
    response.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    response.header("X-Powered-By",' 3.2.1')
    response.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.use('/', function(req, response, next) {
    var path = req.path;
    if (path == '/wechat_outh') {
        next();
        return;
    }

    var account = req.query.account;
    if (account == null) {
        http.send(response, constant.CODE_REQUEST_USERID_ERROR, null);
        return;
    }

    var lastTime = requestInfo[account];
    var nowTime = Date.now();
    if (lastTime) {
        if (nowTime - lastTime < 1000) { //请求间隔小于1秒
            http.send(response, constant.CODE_REQUEST_MUCH, null);
            return;
        }
    }
    requestInfo[account] = nowTime;
    next();
});

//微信登录并校验房间信息
app.get('/wechat_outh',function(req,response){
    var code = req.query.code;
    var os = req.query.os;
    if(code == null || os == null){
        logger.error('http wechat_outh param error');
        http.send(response, constant.CODE_PARAM_INVALID);
        return;
    }
    get_access_token(code,os,function(retCode1, ret1){
        if(ret1){
            var access_token = ret1.access_token;
            var openid = ret1.openid;
            redis.cacheUserAuthInfo(openid, ret1);
            get_state_info(access_token,openid,function(retCode2, ret2){
                if(ret2){
                    var account = "wx_" + openid;
                    redis.getUserInfo(account, function (userInfo) {
                       if (userInfo == null) { //缓存不存在 才更新缓存
                           var userId = String(redis.getUserId());
                           var userInfo = {
                               userId:userId,
                               unionid:ret2.unionid,
                               account:account,
                               name:ret2.nickname,
                               sex:ret2.sex,
                               headimg:ret2.headimgurl,
                               province:ret2.province,
                               city:ret2.city,
                               ip:req.ip,
                               coins:99,
                               gems:10,
                               create_time:Date.now(),
                           };
                           db.setUserInfo(userInfo, null);
                           redis.cacheUserInfo(account, userInfo);
                           redis.cacheUserId();
                       } else {
                           userInfo.ip = req.ip;
                           redis.cacheUserInfo(account, userInfo);
                       }
                    });
                    var result = {
                        account:account,
                        sign:req.ip
                    };
                    http.send(response, retCode2, result);
                    return;
                } else {
                    http.send(response, retCode2);
                    return;
                }
            });
        } else {
            http.send(response, retCode1);
            return;
        }
    });
});

var appInfo = {
    Android:{
        appid:"wxe39f08522d35c80c",
        secret:"fa88e3a3ca5a11b06499902cea4b9c01",
    },
    iOS:{
        appid:"wx3235607d5640d158",
        secret:"cd74de42021e2902358a98e327dab621",
    }
};

function get_access_token(code,os,callback){
    var info = appInfo[os];
    var data = {
        appid:info.appid,
        secret:info.secret,
        code:code,
        grant_type:"authorization_code"
    };

    http.get2("https://api.weixin.qq.com/sns/oauth2/access_token", data, callback, true);
    return;
};

function get_state_info(access_token,openid,callback){
    var data = {
        access_token:access_token,
        openid:openid
    };
    http.get2("https://api.weixin.qq.com/sns/userinfo", data, callback, true);
    return;
};

//微信登录并校验房间信息
app.get('/login',function(req,response){
    // var account = req.query.account;
    // var sign = req.query.sign;
    // if(account == null || sign == null){
    //     logger.error('http login param error');
    //     http.send(response, constant.CODE_PARAM_INVALID);
    //     return;
    // }
    // redis.getUserInfo(account, function (object) {
    //     if (object) {
    //         if (object.ip != sign) {
    //             logger.error('http login param error');
    //             http.send(response, constant.CODE_PARAM_INVALID);
    //             return;
    //         } else {
    //             var notice = "谷子和姜测试数据";
    //             http.send(response, constant.CODE_SUCCESS, {userInfo:object, notice:notice});
    //             return
    //         }
    //     } else {
    //         http.send(response, constant.CODE_REDIS_EMPTY_ERROR);
    //         return;
    //     }
    // });

    var userNo = generateUserNo();
    var userInfo = {
        userId:userNo,
        unionid:userNo,
        account:userNo,
        name:"test"+userNo,
        sex:1,
        headimg:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1521052714196&di=dbc1fd768e1c332a00a7c4b83ef007b4&imgtype=0&src=http%3A%2F%2Fpic20.photophoto.cn%2F20110925%2F0010023291781194_b.jpg",
        province:"广东省",
        city:"深圳市",
        ip:"192.168.0.1",
        coins:99,
        gems:10,
        create_time:Date.now(),
    };
    var notice = "谷子和姜测试数据";
    http.send(response, constant.CODE_SUCCESS, {userInfo:userInfo, notice:notice});

    db.setUserInfo(userInfo, null);
    redis.cacheUserInfo(userNo, userInfo);

    return
});

function generateUserNo(){
    var roomNo = 0;
    for(var j = 5; j > -1; --j){
        roomNo += Math.floor(Math.random()*10) * Math.pow(10, j);
    }
    if (roomNo < 100000) {
        roomNo += 100000;
    }
    roomNo = String(roomNo);
    logger.debug('generateUserNo', roomNo);
    return roomNo;
};

//微信登录并校验房间信息
app.get('/update_location',function(req,response) {
    var account = req.query.account;
    var pro = req.query.pro;
    var city = req.query.city;
    var lati = req.query.lati;
    var longi = req.query.longi;
    if(account == null || lati == null || longi == null){
        logger.error('http login param error');
        http.send(response, constant.CODE_PARAM_INVALID);
        return;
    }
    redis.getUserInfo(account, function (object) {
        if (object) {
            object.province = pro;
            object.city = city;
            object.lati = lati;
            object.longi = longi;
            redis.cacheUserInfo(account, object);
        }
        http.send(response, constant.CODE_SUCCESS);
        return;
    });
});

//创建房间
app.get('/create_room',function(req,response){
    var userId = req.query.userId;
    var gameType = req.query.gameType;//游戏类型 10牛牛 20炸金花 30斗地主 40麻将
    var roomType = req.query.roomType;//房间类型 1自由抢庄 2霸王庄
    var jushu = req.query.jushu;//局数
    jushu = 2; //todo 测试
    var fangfei = req.query.fangfei;//1房费房主 2房费均摊

    var difen = req.query.difen;//局数
    if (difen == null) difen = 1;

    var roomInfo = {
        gameType:gameType,
        roomType:roomType,
        jushu:jushu,
        fangfei:fangfei,
        difen:difen,
    };
    var type = 0;
    if (gameType == 10) {//牛牛
        if (roomType == 1) {//牛牛上庄
            type = 11;
        } else if (roomType == 2) {//固定庄家
            type = 12;
        } else if (roomType == 3) {//明牌抢庄
            type = 13;
        }
        roomInfo.tuizhu = req.query.tuizhu;//最大倍数(牛牛);
    } else if (gameType == 20){//炸金花
        type = 21;
        roomInfo.roundLimit = req.query.roundLimit;//必闷限制(金花)
    } else if (gameType == 30){//斗地主 是否带癞子
        type = 31;
        roomInfo.laiZi = req.query.laiZi;//是否带癞子(地主);
    }else if (gameType == 40){
        if (roomType == 1) {
            type = 41; //蚌埠麻将
            roomInfo.hua = 0;
        } else if (roomType == 2) {
            type = 42; //怀远麻将
            roomInfo.hua = 1; //带花
        }
        roomInfo.renshu = req.query.renshu;//可以三人玩或者四人玩
        roomInfo.dingwei = req.query.dingwei;//1表示开启强制定位
    }
    roomInfo.type = type;
    room_service.createRoom(userId, roomInfo, function (code, ret) {
        logger.debug('createRoom', code);
        http.send(response, code, ret);
        return;
    });
});

//加入房间
app.get('/join_room',function(req,response){
    var userId = req.query.userId;
    var roomNo = req.query.roomNo;//游戏类型 10牛牛 20炸金花 30斗地主
    if(userId == null || roomNo == null){
        logger.error('http join_room param error');
        http.send(response, constant.CODE_PARAM_INVALID);
        return;
    }
    room_service.enterRoom(userId, roomNo, function (code, ret) {
        logger.debug('enterRoom', code);
        http.send(response, code, ret);
        return;
    });
});

//房间列表
app.get('/list_room',function(req,response){
    var userId = req.query.userId;
    redis.getUserRoomInfo(userId, function (list) {
        http.send(response, constant.CODE_SUCCESS, {list:list});
        return;
    });
});

//获取战绩
app.get('/list_history',function(req,response){
    var userId = req.query.userId;
    db.getUserRoomRecords(userId, function (code, ret) {
        logger.debug('list_history', code);
        http.send(response, code, ret);
        return;
    });
});

//注册game_server
app.get('/register_server',function(req,response){
    var number = req.query.id;
    var ip = req.query.gameIP
    var httpPort = req.query.httpPort;
    var socketPort = req.query.socketPort;
    var load = req.query.load;

    var id = ip + ":" + httpPort;
    var serverMap  = room_service.serverMap;

    if(serverMap[id]){ //该id的服务器信息存在
        var info = serverMap[id];
        if(info.httpPort != httpPort || info.socketPort != socketPort){
            logger.error('register_server duplicate', id);
            http.send(response, constant.CODE_REGISTER_SERVER_ERROR);
            return;
        }
        info.load = load;//已经有多少房间
        http.send(response, constant.CODE_SUCCESS, {ip:ip});
        return;
    }

    serverMap[id] = {
        number:number,
        ip:ip,
        httpPort:httpPort,
        socketPort:socketPort,
        load:load
    };
    room_service.ROOM_PRI_KEY = config.ROOM_PRI_KEY;
    // user_service.ACCOUNT_PRI_KEY = config.ACCOUNT_PRI_KEY;

    logger.debug("game server registered", id);
    http.send(response, constant.CODE_SUCCESS, {ip:ip});
    return;
});
